<?php
# ***** BEGIN LICENSE BLOCK *****
# This file is part of "myWiWall".
# Copyright (c) 2007-2008 CRP Henri Tudor and contributors.
# All rights reserved.
#
# "myWiWall" is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as published by
# the Free Software Foundation.
# 
# "myWiWall" is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with "myWiWall"; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# ***** END LICENSE BLOCK *****


/**
 * The Users Module class regroups all actions that are involved in the users management of the portal.
 *
 * @author Laurent Haan <laurent.haan@gmail.com>
 * @author J�r�me Bogaerts <jerome.bogaerts@gmail.com>
 * @package mywiwall.actions
 */
class Users
{
	/**
	 * The index action is the default action of the Users module. It should be triggered through
	 * an HTTP GET Request in order to access the application's login form.
	 *
	 * @param string $ref The action from which the user-agent was redirected as a 'module/action' formatted string.
	 */
	public function index($ref)
	{
		// for openid sso
		if (OPENID_SSO_MODE) {
			if (isset($_COOKIE['default_openid'])) {
				self::authenticate('', '', '', $_COOKIE['default_openid']);
				exit;
			}
		}

		// Bad authentication ?
		if(isset($_SESSION['isError']))
		{
			$isError = $_SESSION['isError'];
			$message = $_SESSION['message'];
			
			unset($_SESSION['isError']);
			unset($_SESSION['message']);
		}
		else
		{
			$isError = false;
		}

		// Was installation folder deleted by the portal administrator ?
		$installWarning = file_exists(dirname(__FILE__) . '/../install');
		
		// Was root user's password changed by the administrator ?
		$rootUserWarning = Util::checkUserIdentifiers('root', md5('root'));
		
		$redirectionAfterLogin = Util::getActionString($ref);
		require(DefaultFC::getView('login.tpl'));
	}
	
	/**
	 * The authenticate action has to be triggered through an HTTP POST Request, only if the user agent
	 * comes directly from the index (login form) action.
	 *
	 * @param string $username The username provided through the login form.
	 * @param string $password The password provided through the login form.
	 * @param string $ref The action where the user-agent has to be redirect if the authentication process is a success.
	 */
	public function authenticate($username, $password, $ref, $openid)
	{
		if (!empty($openid)) {
			$oid = new Openid();
			$oid->try_auth($openid);
			exit;
		}
		
		Auth::login($username, $password);
		
		if(Auth::isAuth())
		{
			// Authentication process succeeded.

			// We log the connection if necessary.
			// FIXME Use a real log library to log messages.
			if (LOGS_USERS)
				$this->logConnection();
			
			// Redirection in the portal.
			DefaultFC::redirection($ref);
			exit;
		}
		else
		{
			$_SESSION['isError'] = true;
			$_SESSION['message'] = __("Wrong login or password. Please try again.");
			
			DefaultFC::redirection('users/index');
			exit;
		}
	}
	
	/**
	 * The logout action has to be triggered through an HTTP GET Request. It allows the user
	 * to quit gracefully the system.
	 *
	 */
	public function logout()
	{
		// for openid sso
		if (OPENID_SSO_MODE) {
	  		setcookie('default_openid', false, 0, HttpRequest::getPathUrl());
		}

		Auth::logout();
		DefaultFC::redirection('users/index');
	}
	
	public function preferences()
	{
		// Bad authentication ?
		if(isset($_SESSION['isError']))
		{
			$isError = $_SESSION['isError'];
			$message = $_SESSION['message'];
			
			unset($_SESSION['isError']);
			unset($_SESSION['message']);
		}
		else
		{
			$isError = false;
		}
		
		
		// Determine if the view must allow the user to manage widgets.
		$widgetManagement = false;
		if (Auth::isAdmin() || Auth::isGod())
			$widgetManagement = true;
				
		$availableLanguages = Util::getAvailableLanguages();
		$userLanguage = Auth::getLanguage();
		$openId = Auth::getOpenId();
		
		require(DefaultFC::getView('preferences.tpl'));
	}
	
	public function editPreferences()
	{
		// Note : because the number of parameters may vary in the future,
		// I will use $_POST to retrieve request params.
		$currentUser = Auth::getUserName();
		
		// -- Identifiers.
		$oldPassword = $_POST['old_password'];
		$newPassword = $_POST['new_password'];
		$confirmPassword = $_POST['new_password_confirm'];
		
		// OpenId
		$openId = (isset($_POST['openid'])) ? $_POST['openid'] : '';
		
		// -- I18n.
		$language = $_POST['language'];
		
		try
		{
			UsersManagement::updatePreferences(array('old_password' 		=> $oldPassword,
											  		 'new_password' 		=> $newPassword,
													 'confirm_password' 	=> $confirmPassword,
													 'language' 			=> $language,
													 'openid' 				=> $openId,
													 'username' 			=> $currentUser,
													 'userid'				=> Auth::getUserId()));
			
			// Don't forget to change the language before generating the message to
			// the user.
			$GLOBALS['lang'] = $language;
			l10n::init();
			l10n::set(dirname(__FILE__).'/../locales/'.$GLOBALS['lang'].'/messages');
			
			$_SESSION['isError'] = false;
			$_SESSION['message'] = __("Your preferences were successfuly changed.");
		}
		catch (PreferencesException $e)
		{
			$_SESSION['isError'] = true;
			$_SESSION['message'] = '';
			
			switch ($e->getCode())
			{
				case PreferencesException::WRONG_OLD_PASSWORD:
					$_SESSION['message'] = __("Wrong old password. Please try again.");
				break;
				
				case PreferencesException::NEW_PASSWORD_TOO_SHORT:
					$_SESSION['message'] = sprintf(__("The new password you provided is too short and must be at least composed of %s characters."), PASSWORDS_MIN_LENGTH);
				break;
				
				case PreferencesException::NEW_PASSWORDS_DIFFERENT:
					$_SESSION['message'] = __("The new and confirmation passwords are different. Please try again.");
				break;
			}
		}
		
		DefaultFC::redirection('users/preferences');
	}
	
	public function register()
	{
		$displayOldValues = false;
		require_once (DefaultFC::getView('register.tpl'));
	}
	
	public function createAccount()
	{
		// Note : again, because the number of parameters may vary in the future,
		// I will use $_POST to retrieve request params.
		$username = $_POST['username'];
		$password = $_POST['password'];
		$confirmPassword = $_POST['password_confirm'];
		$openId = isset($_POST['openid']) ? $_POST['openid'] : '';
		$userType = 0;
		
		try
		{
			UsersManagement::addUser(array('username' 			=> $username,
									 	   'password' 			=> $password,
										   'confirm_password'	=> $confirmPassword,
										   'openid'				=> $openId,
										   'rights'				=> $userType,
										   'copname'			=> 'cop1'),
									 true);

			$_SESSION['isError'] = false;
			$_SESSION['message'] = __("Your account has been successfuly created.");						 
									 
			DefaultFC::redirection('wall/index');
		}
		catch(UsersManagementException $e)
		{
			$isError = true;
			$message = Util::buildAddEditUserErrorMessage($e);
				
			// Escaping to reinsert in form ...
			$username 	= htmlspecialchars($username, ENT_QUOTES, 'UTF-8');
			$openId 	= htmlspecialchars($openId, ENT_QUOTES, 'UTF-8');
			
			$displayOldValues = true;
			
			require_once(DefaultFC::getView('register.tpl'));
		}
	}
	
	private function logConnection()
	{
		if (LOGS_USERS)
		{
			if ($fp = @fopen(LOGS_USERS_SRC, 'a+'))
			{
				@fwrite($fp, sprintf("[%s] Login '%s'\r\n", 
									date('d/m/Y H:i:s'), Auth::getUserName()));
				@fclose($fp);
			}
		}
	}
}
?>